package common

import (
	"context"
	"fmt"
	"gfdemo/internal/dao"
	"gfdemo/internal/model/entity"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gcfg"
	"github.com/gogf/gf/v2/os/gcron"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/glog"
)

type mihomoConn struct {
	DownloadTotal int64
	UploadTotal   int64
	Memory        int64
	Connections   []entity.MihoRow
}

func mihomoSync() {
	ctx := gctx.New()
	c := gcfg.Instance()
	if c.Available(ctx) {
		data, err := c.Get(ctx, "godemo.mihomoUrl")
		if err != nil {
			glog.Info(ctx, "没有配置 godemo.mihomoUrl 跳过注册 mihomo 任务注册!")
		}
		if data.IsNil() {
			glog.Warningf(ctx, "没有配置 godemo.mihomoUrl 跳过注册 mihomo 任务注册!")
			return
		}
		glog.Infof(ctx, "当前 mihomoUrl 为 [ %s ] ,已注册配置同步任务!", data.String())
		gcron.AddSingleton(ctx, "*/3 * * * * *", func(ctx context.Context) {
			rep, err := g.Client().Get(ctx, data.String()+"/connections")
			if err != nil {
				glog.Warningf(ctx, "请求 mihomo 失败: %s", err.Error())
			}
			defer rep.Close()
			var (
				add = 0
				mod = 0
			)
			data := &mihomoConn{}
			gjson.DecodeTo(rep.ReadAllString(), data)
			dc := dao.MihoRow.Ctx(ctx)
			// .Cache(gdb.CacheOption{
			// 	Duration: time.Hour,
			// 	Name:     "miho-update-cache",
			// 	Force:    false,
			// })
			//MihoMoConnIds.Clear()
			for i := 0; i < len(data.Connections); i++ {
				c := data.Connections[i]
				tmp := entity.MihoRow{}
				tid := fmt.Sprintf("%s-%s", c.Start.Format("Y-m-d"), c.Id)
				dc.Where("id=?", tid).Scan(&tmp)
				c.Uuid = c.Id
				c.Id = tid
				if tmp.Id != "" {
					// 其他字段不会变,不需要浪费带宽
					if tmp.Upload != c.Upload || tmp.Download != c.Download {
						dc.Fields("upload,download").Data(&c).Where("id=?", tid).Update()
						mod++
					}
				} else {
					_, err := dc.Data(&c).Insert()
					if err != nil {
						glog.Error(ctx, "添加数据出错:", err)
					}
					add++
				}
			}
			glog.Debugf(ctx, "下载量: %d, 上传量: %d, 内存: %d, 数据量: %d,新增: %d,修改: %d", data.DownloadTotal, data.UploadTotal, data.Memory, len(data.Connections), add, mod)
		})
	}
}
